package StudentInfoApp;

import java.io.*;
import java.util.*;

public class StudentInfoApp {
    public static void main(String[] args) {
        Scanner scanner = new Scanner(System.in);
        String fileName = "student_info.txt";

        // 第1部分：从文件写入和读取
        System.out.println("请输入要写入文件的内容：");
        String userInput = scanner.nextLine();
        writeToFile(fileName, userInput);
        System.out.println("文件内容：");
        readFile(fileName);

        // 第2部分：输入学生信息并按分数排序
        List<Student> students = new ArrayList<>();
        for (int i = 0; i < 5; i++) {
            System.out.print("请输入第" + (i + 1) + "个学生的姓名：");
            String name = scanner.nextLine();
            System.out.print("请输入第" + (i + 1) + "个学生的成绩：");
            double score = scanner.nextDouble();
            scanner.nextLine(); // Consume newline
            students.add(new Student(name, score));
        }

        students.sort((s1, s2) -> Double.compare(s2.getScore(), s1.getScore()));

        for (Student student : students) {
            writeToFile(fileName, student.getName() + ", " + student.getScore(), true);
        }

        System.out.println("更新后的文件内容：");
        readFile(fileName);
    }

    private static void writeToFile(String fileName, String content) {
        try (BufferedWriter writer = new BufferedWriter(new FileWriter(fileName))) {
            writer.write(content);
        } catch (IOException e) {
            e.printStackTrace();
        }
    }

    private static void writeToFile(String fileName, String content, boolean append) {
        try (BufferedWriter writer = new BufferedWriter(new FileWriter(fileName, append))) {
            writer.newLine();
            writer.write(content);
        } catch (IOException e) {
            e.printStackTrace();
        }
    }

    private static void readFile(String fileName) {
        try (BufferedReader reader = new BufferedReader(new FileReader(fileName))) {
            String line;
            while ((line = reader.readLine()) != null) {
                System.out.println(line);
            }
        } catch (IOException e) {
            e.printStackTrace();
        }
    }
}

class Student {
    private String name;
    private double score;

    public Student(String name, double score) {
        this.name = name;
        this.score = score;
    }

    public String getName() {
        return name;
    }

    public double getScore() {
        return score;
    }
}
